package org.jgs1904.chanmufeng;

import java.io.*;

/**
 * 枚举式单例1
 *
 * @author: 默苍璃
 * @date: 2024-07-01 15:49
 */
public class EnumSingleObject implements Serializable {
    private EnumSingleObject() {
    }

    enum SingletonEnum {
        INSTANCE;

        private EnumSingleObject instance;

        private SingletonEnum() {
            instance = new EnumSingleObject();
        }

        public EnumSingleObject getInstance() {
            return INSTANCE.instance;
        }
    }

    // 对外暴露一个获取EnumSingleObject对象的静态方法
    public static EnumSingleObject getInstance() {
        return SingletonEnum.INSTANCE.getInstance();
    }

    // 测试序列化能否破坏
    public static void main(String[] args) {
        EnumSingleObject s1 = EnumSingleObject.getInstance();
        EnumSingleObject s2 = null;

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("SeriableSingleton.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s1);
            oos.flush();
            oos.close();
            fos.close();

            FileInputStream fis = new FileInputStream("SeriableSingleton.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            s2 = (EnumSingleObject) ois.readObject();
            ois.close();
            fis.close();

            // 输出为false
            System.out.println(s1 == s2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

